from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime, timedelta
from sqlalchemy import func

from ..db import get_db
from ..models.models import Admin, Student, Room, Building, Interest, RoomAssignment
from ..schemas import (
    AdminResponse, StudentResponse,
    BuildingCreate, BuildingResponse,
    RoomCreate, RoomResponse,
    InterestCreate, InterestResponse,
    BuildingStatsResponse
)
from ..auth import get_current_admin
from ..services.admin_service import AdminService

router = APIRouter(
    prefix="/admin",
    tags=["系统管理"]
)

# 管理员账户管理
@router.get("/me", response_model=AdminResponse)
async def read_admin_me(
    current_admin: Admin = Depends(get_current_admin)
):
    """获取当前管理员信息"""
    return current_admin

@router.get("/admins", response_model=List[AdminResponse])
async def list_admins(
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取所有管理员列表（仅超级管理员可访问）"""
    if not current_admin.is_super_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="需要超级管理员权限"
        )
    return db.query(Admin).all()

# 学生管理
@router.get("/students", response_model=List[StudentResponse])
async def list_students(
    grade: Optional[int] = None,
    major: Optional[str] = None,
    has_room: Optional[bool] = None,
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """查询学生列表"""
    query = db.query(Student)
    
    if grade:
        query = query.filter(Student.grade == grade)
    if major:
        query = query.filter(Student.major == major)
    if has_room is not None:
        if has_room:
            query = query.filter(Student.room_assignment.has())
        else:
            query = query.filter(~Student.room_assignment.has())
            
    return query.all()

@router.get("/students/{student_id}", response_model=StudentResponse)
async def get_student_detail(
    student_id: int,
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取学生详细信息"""
    student = db.query(Student).filter(Student.id == student_id).first()
    if not student:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="学生不存在"
        )
    return student

@router.post("/students/{student_id}/deactivate", response_model=StudentResponse)
async def deactivate_student(
    student_id: int,
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """停用学生账号"""
    student = db.query(Student).filter(Student.id == student_id).first()
    if not student:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="学生不存在"
        )
        
    student.is_active = False
    db.commit()
    db.refresh(student)
    return student

# 宿舍楼管理
@router.post("/buildings", response_model=BuildingResponse)
async def create_building(
    building: BuildingCreate,
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """创建新宿舍楼"""
    db_building = Building(**building.dict())
    db.add(db_building)
    db.commit()
    db.refresh(db_building)
    return db_building

@router.get("/buildings/stats", response_model=List[BuildingStatsResponse])
async def get_all_buildings_stats(
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取所有宿舍楼统计信息"""
    admin_service = AdminService()
    buildings = db.query(Building).all()
    
    stats = []
    for building in buildings:
        building_stats = admin_service.get_building_statistics(db, building.id)
        if building_stats:
            stats.append(building_stats)
            
    return stats

# 房间管理
@router.post("/rooms", response_model=RoomResponse)
async def create_room(
    room: RoomCreate,
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """创建新房间"""
    # 检查宿舍楼是否存在
    building = db.query(Building).filter(Building.id == room.building_id).first()
    if not building:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="宿舍楼不存在"
        )
        
    # 检查房间号是否已存在
    existing_room = (
        db.query(Room)
        .filter(
            Room.building_id == room.building_id,
            Room.room_number == room.room_number
        )
        .first()
    )
    if existing_room:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="房间号已存在"
        )
        
    db_room = Room(**room.dict())
    db.add(db_room)
    db.commit()
    db.refresh(db_room)
    return db_room

@router.delete("/rooms/{room_id}")
async def delete_room(
    room_id: int,
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """删除房间（仅限空房间）"""
    room = db.query(Room).filter(Room.id == room_id).first()
    if not room:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="房间不存在"
        )
        
    if room.current_occupancy > 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="无法删除已占用的房间"
        )
        
    db.delete(room)
    db.commit()
    return {"status": "success"}

# 兴趣标签管理
@router.post("/interests", response_model=InterestResponse)
async def create_interest(
    interest: InterestCreate,
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """创建新兴趣标签"""
    # 检查标签是否已存在
    existing_interest = db.query(Interest).filter(Interest.name == interest.name).first()
    if existing_interest:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="兴趣标签已存在"
        )
        
    db_interest = Interest(**interest.dict())
    db.add(db_interest)
    db.commit()
    db.refresh(db_interest)
    return db_interest

@router.delete("/interests/{interest_id}")
async def delete_interest(
    interest_id: int,
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """删除兴趣标签"""
    interest = db.query(Interest).filter(Interest.id == interest_id).first()
    if not interest:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="兴趣标签不存在"
        )
        
    # 检查是否有学生使用此标签
    if interest.students:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="无法删除已被使用的标签"
        )
        
    db.delete(interest)
    db.commit()
    return {"status": "success"}

@router.get("/statistics")
async def get_system_statistics(
    current_admin: Admin = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取系统统计信息"""
    total_students = db.query(Student).count()
    active_students = db.query(Student).filter(Student.is_active == True).count()
    total_rooms = db.query(Room).count()
    
    # 计算入住率
    total_capacity = db.query(Room).with_entities(func.sum(Room.capacity)).scalar() or 0
    total_occupancy = db.query(Room).with_entities(func.sum(Room.current_occupancy)).scalar() or 0
    occupancy_rate = round(total_occupancy / total_capacity * 100, 2) if total_capacity > 0 else 0
    
    # 获取各年级学生数量
    grade_stats = (
        db.query(Student.grade, func.count(Student.id))
        .group_by(Student.grade)
        .all()
    )
    
    # 获取各专业学生数量
    major_stats = (
        db.query(Student.major, func.count(Student.id))
        .group_by(Student.major)
        .all()
    )
    
    return {
        "total_students": total_students,
        "active_students": active_students,
        "total_rooms": total_rooms,
        "total_capacity": total_capacity,
        "total_occupancy": total_occupancy,
        "occupancy_rate": occupancy_rate,
        "grade_distribution": dict(grade_stats),
        "major_distribution": dict(major_stats)
    } 